﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QuickApp.Core;
using EfSearchModel.Model;
using QuickApp.MVCControl;
using Resto.CostControl.Core;
using QuickApp.MVCControl.Form;
using System.Data.SqlClient;
using System.Data.Entity;
using Resto.CostControl.Core.Models;

namespace Resto.CostControl.Web.Controllers
{
    public class DishDeliveryController : Controller
    {
        private readonly IRepository<DishDelivery> _Repo;
        private readonly IRepository<DishDeliveryItem> _RepoItem;
        private readonly IRepository<Storage> _RepoStorage;
        private readonly IRepository<StockRecord> _RepoStockRecord;
        private readonly IUnitOfWork _UnitOfWork;

        public DishDeliveryController(IRepository<DishDelivery> repo, IRepository<DishDeliveryItem> repoItem, IRepository<Storage> repoStorage, IRepository<StockRecord> RepoStockRecord, UnitOfWork unitOfWork)
        {
            _Repo = repo;
            _RepoItem = repoItem;
            _RepoStorage = repoStorage;
            _RepoStockRecord = RepoStockRecord;
            _UnitOfWork = unitOfWork;
        }

        public ActionResult Index()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Index(DWZPageInfo pageInfo, DWZQueryModel where)
        {
            //where.AddItem("OrderState", null);
            var list = _Repo.GetPageable(pageInfo.ToPageInfo(), where);
            var fdata = pageInfo.ToFlexiGridData<DishDelivery>(list.Page.ToList(), list.Total);
            return Json(fdata);
        }

        public ActionResult Edit(string Id, string siteId, string date)
        {
            DishDelivery data = null;
            if (!string.IsNullOrWhiteSpace(Id))
            {
                data = _Repo.Find(Id);
            }
            else
            {
                data = new DishDelivery();
                data.Id = Guid.NewGuid().ToString();
                data.State = "Draft";
                if (!string.IsNullOrEmpty(siteId))
                {
                    data.SiteID = ViewBag.SiteID = siteId;
                    ViewBag.Date = date;
                    data.Date = DateTime.Parse(date);
                }
                else
                {
                    data.Date = DateTime.Now;
                }
            }
            return View(data);
        }

        [HttpPost]
        public JsonResult Save(DishDelivery data, IList<DishDeliveryItem> MaterialList)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            if (ModelState.IsValid)
            {
                try
                {
                    if (_Repo.Find(data.Id) == null)
                    {
                        _Repo.Insert(data);
                    }
                    else
                    {
                        data.Date = DateTime.Now;
                        data = _Repo.Find(data.Id);
                        TryUpdateModel(data);

                        _RepoItem.DeleteAll(m => m.OrderId == data.Id);
                    }

                    if (MaterialList != null)
                    {
                        foreach (var m in MaterialList)
                        {
                            m.OrderId = data.Id;
                            m.MaterialId = m.Id;
                            m.Id = Guid.NewGuid().ToString();
                            m.State = data.State;
                            _RepoItem.Insert(m);

                            //保存库存记录
                            StockRecord StockRecorddate = new StockRecord()
                            {
                                Id = Guid.NewGuid().ToString(),
                                MaterialId = m.MaterialId,
                                Type = "物流送货",
                                Count = m.DeliveryCount,
                            };
                            _RepoStockRecord.Insert(StockRecorddate);
                        }
                    }

                    _UnitOfWork.Commit();
                    msg.IsSuccess = true;
                    msg.Msg = "操作成功";
                }
                catch (Exception ex)
                {
                    msg.IsSuccess = false;
                    msg.Msg = "操作失败：" + ex.Message;
                }
            }

            return Json(msg);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Delete(string id)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            if (!string.IsNullOrEmpty(id))
            {
                try
                {
                    _Repo.Delete(id);
                    _UnitOfWork.Commit();
                    msg.IsSuccess = true;
                    msg.Msg = "操作成功";
                }
                catch
                {
                    msg.IsSuccess = false;
                    msg.Msg = "操作失败,请稍后重试！";
                }
            }
            else
            {
                msg.IsSuccess = false;
                msg.Msg = "参数错误";
            }
            return Json(msg);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult MaterialList(DWZPageInfo pageInfo, DWZQueryModel where)
        {
            var list = _RepoItem.GetPageable(pageInfo.ToPageInfo(), where);
            var fdata = pageInfo.ToFlexiGridData<DishDeliveryItem>(list.Page.ToList(), list.Total);
            return Json(fdata);
        }

        public ActionResult EditList()
        {
            return View();
        }

        [Ninject.Inject]
        public DbContext context { get; set; }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult EditList(string parentId, string siteId, DateTime? date, DWZPageInfo pageInfo, DWZQueryModel where)
        {
            // 从发货计划中产生明细
            if (!string.IsNullOrEmpty(siteId))
            {
                string sql = @"SELECT dbo.Materials.Id, '' as OrderId, dbo.Materials.Id as MaterialId,
                                dbo.Materials.Code, dbo.Materials.Name, 0.0 as Price, dbo.Materials.Category, SUM(dbo.DishMaterials.Weight * dbo.DishOrderItems.Count) AS OrderCount,
                                SUM(dbo.DishMaterials.Weight * dbo.DishOrderItems.Count) as DeliveryCount,0.0 as SignCount, 'Draft' as State
	                                FROM  dbo.Materials 
	                                INNER JOIN dbo.DishMaterials ON dbo.Materials.Id = dbo.DishMaterials.MaterialId 
	                                INNER JOIN dbo.DishOrderItems ON dbo.DishMaterials.DishId = dbo.DishOrderItems.DishId
                                Where dbo.DishOrderItems.Date = @Date AND dbo.DishOrderItems.SiteId = @SiteId
                                GROUP BY dbo.DishOrderItems.Date, dbo.DishOrderItems.SiteId,dbo.Materials.Id, dbo.Materials.Category, dbo.Materials.Code, dbo.Materials.Name
                                ";

                List<SqlParameter> plist = new List<SqlParameter>();
                plist.Add(new SqlParameter("@Date", date.Value));
                plist.Add(new SqlParameter("@SiteId", siteId));

                var list = context.Database.SqlQuery<DishDeliveryItem>(sql, plist.ToArray()).ToList();
                var fdata = pageInfo.ToFlexiGridData<DishDeliveryItem>(list, list.Count);
                return Json(fdata);
            }
            else
            {
                where.AddItem("OrderId", parentId == "" ? null : parentId);
                var list = _RepoItem.GetPageable(pageInfo.ToPageInfo(), where);
                var fdata = pageInfo.ToFlexiGridData<DishDeliveryItem>(list.Page.ToList(), list.Total);
                return Json(fdata);
            }

        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult DeleteItem(string Id)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            if (!string.IsNullOrEmpty(Id))
            {
                try
                {
                    _RepoItem.Delete(Id);
                    _UnitOfWork.Commit();

                }
                catch
                {
                    msg.IsSuccess = false;
                    msg.Msg = "操作失败,请稍后重试！";
                }
            }
            else
            {
                msg.IsSuccess = false;
                msg.Msg = "参数错误";
            }
            return Json(msg);
        }

        public JsonResult MaterialDelivery(string Id)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            try
            {
                var data = _Repo.Find(Id);
                data.State = "Delivery";

                var itemList = _RepoItem.FindAll(m => m.OrderId == Id).ToList();
                foreach (var childitem in itemList)
                {
                    var childdata = _RepoItem.Find(childitem.Id);
                    childdata.State = "Delivery";

                    var Sordate = _RepoStorage.Find(s => s.MaterialId == childitem.MaterialId);
                    Sordate.ActualSorage -= childitem.DeliveryCount;
                }

                _UnitOfWork.Commit();
                msg.IsSuccess = true;
                msg.Msg = "操作成功";
            }
            catch (Exception ex)
            {
                msg.IsSuccess = false;
                msg.Msg = "操作失败:" + ex.Message;
            }

            return Json(msg);
        }
    }
}